package com.PuzGame.combinenumbers.Activities;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.PuzGame.combinenumbers.ChallengeMetaDataAdapter;
import com.PuzGame.combinenumbers.ChallengeMetaDataItem;
import com.PuzGame.combinenumbers.ChallengeeLevel;
import com.PuzGame.combinenumbers.ChallengerLevel;
import com.PuzGame.combinenumbers.ComparatorAdapter;
import com.PuzGame.combinenumbers.FriendToChallengItem;
import com.PuzGame.combinenumbers.FriendsList;
import com.PuzGame.combinenumbers.FriendsToChallengeAdapter;
import com.PuzGame.combinenumbers.Level;
import com.PuzGame.combinenumbers.Level.LevelType;
import com.PuzGame.combinenumbers.R;
import com.PuzGame.combinenumbers.Tools;
import com.PuzGame.combinenumbers.Interfaces.IGetDataResponse;
import com.PuzGame.combinenumbers.Interfaces.IPostDataResponse;
import com.PuzGame.combinenumbers.ServerCommunication.GetDataAsyncTask;
import com.PuzGame.combinenumbers.ServerCommunication.PostDataAsyncTask;
import com.PuzGame.combinenumbers.ServerCommunication.GetAndPostItems.GetPost_Challenge;
import com.PuzGame.combinenumbers.ServerCommunication.GetAndPostItems.Get_ChallengesMetaDatas;
import com.PuzGame.combinenumbers.ServerCommunication.GetAndPostItems.Get_ChallengesMetaDatas.ChallengeMetaData;
import com.PuzGame.combinenumbers.ServerCommunication.GetAndPostItems.Get_FriendsDifficultyLevels;
import com.PuzGame.combinenumbers.ServerCommunication.GetAndPostItems.Get_FriendsDifficultyLevels.FriendDifficultyLevel;
import com.PuzGame.combinenumbers.ServerCommunication.GetAndPostItems.Get_UserData;
import com.PuzGame.combinenumbers.customViews.CustomPopupWindow;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.LoginButton;
import com.facebook.widget.ProfilePictureView;
import com.google.gson.Gson;

public class ChallengesArenaActivity extends Activity {

	private ListView FriendsToChallengeListView;
	private ListView ChallengesMetaDataListView;

	private FriendsToChallengeAdapter FriendsToChallengeAdapter;
	private ChallengeMetaDataAdapter ChallengesMetaDataAdapter;

	FriendsList friendsList;
	ArrayList<ChallengeMetaDataItem> ChallengesMetaDataList;

	private final String PENDING_ACTION_BUNDLE_KEY = "com.PuzGame.combinenumbers:PendingAction";

	private LoginButton loginButton;
	private ProfilePictureView profilePictureView;
	private PendingAction pendingAction = PendingAction.NONE;
	//private GraphUser user;


	private RadioGroup radioGroup;
	private LinearLayout firendlist;
	private LinearLayout challengelist;
	private Button button2;

	private Get_UserData userData;


	private Context context = this;

	private enum PendingAction {
		NONE,
		POST_PHOTO,
		POST_STATUS_UPDATE
	}
	private UiLifecycleHelper uiHelper;

	private ChallengerLevel lvl;
	public static final int CHALLENGER_REQUEST_CODE = 1;
	public static final int CHALLENGEE_REQUEST_CODE = 2;

	private boolean ChallengeLevelExists()
	{
		if(lvl!=null && !lvl.IsDone() )
		{
			return true;
		}

		ChallengerLevel RestoredLevel = null;

		String json = RestoreChallengeLevel();

		RestoredLevel = (ChallengerLevel) ChallengerLevel.fromJson(json, ChallengerLevel.class);

		if(RestoredLevel != null)
		{
			lvl = RestoredLevel;
			if(!lvl.IsDone())
				return true;
		}
		return false;

	}

	private String RestoreChallengeLevel()
	{

		SharedPreferences settings = getSharedPreferences("ChallengeInfo", MODE_PRIVATE);
		String res = settings.getString("CompleteLevel", "");
		Log.i("SharedPreferences", "Restored level:"+ res);
		return res;

	}

	public void DeleteChallengeLevel()
	{
		SharedPreferences settings = getSharedPreferences("ChallengeInfo", MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();

		editor.remove("CompleteLevel");

		editor.commit();
	}

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
		@Override
		public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
			Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
		}

		@Override
		public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
			Log.d("HelloFacebook", "Success!");
		}
	};

	public static void showHashKey(Context context) {
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(
					"com.PuzGame.combinenumbers", PackageManager.GET_SIGNATURES); //Your            package name here
			for (android.content.pm.Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				Log.i("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
			}
		} catch (NameNotFoundException e) {
		} catch (NoSuchAlgorithmException e) {
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		uiHelper = new UiLifecycleHelper(this, callback);
		uiHelper.onCreate(savedInstanceState);

		DeleteChallengeLevel();



		if (savedInstanceState != null) {
			String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
			pendingAction = PendingAction.valueOf(name);
		}

		showHashKey(this);

		setContentView(R.layout.activity_challenges_arena_bak);


		firendlist = (LinearLayout) findViewById(R.id.Friendslist);
		challengelist = (LinearLayout) findViewById(R.id.Challengeslist);
		radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged( RadioGroup group, int checkedId) {

				View radioButton = group.findViewById(checkedId);
				int idx = radioGroup.indexOfChild(radioButton);
				if(idx == 0)
				{
					firendlist.setVisibility(View.VISIBLE);
					challengelist.setVisibility(View.GONE);
				}
				else
				{
					firendlist.setVisibility(View.GONE);
					challengelist.setVisibility(View.VISIBLE);
				}
			}
		});


		button2 = (Button) findViewById(R.id.button2);
		button2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(lvl.getType() == LevelType.CHALLENGER)
				{
					Intent intent = new Intent(getBaseContext(), ChallengerActivity.class);

					String jsonLevel = RestoreChallengeLevel();
					intent.putExtra("PreparedChallengeLevel", jsonLevel);

					Gson gson = new Gson();
					String jsonUserData =  gson.toJson(userData.userData);
					intent.putExtra("PreparedUserData", jsonUserData);

					startActivityForResult(intent, CHALLENGER_REQUEST_CODE);
				}
				else
				{
					Intent intent = new Intent(getBaseContext(), ChallengeeActivity.class);

					String jsonLevel = RestoreChallengeLevel();
					intent.putExtra("PreparedChallengeLevel", jsonLevel);

					Gson gson = new Gson();
					String jsonUserData =  gson.toJson(userData.userData);
					intent.putExtra("PreparedUserData", jsonUserData);

					startActivityForResult(intent, CHALLENGEE_REQUEST_CODE);
				}
			}
		});

		FriendsToChallengeListView = (ListView)findViewById(R.id.listView_FriendsToChallenge);
		ChallengesMetaDataListView = (ListView)findViewById(R.id.listView_ChallengesMetaData);

		loginButton = (LoginButton) findViewById(R.id.login_button);
		loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
			@Override
			public void onUserInfoFetched(GraphUser user) {
				if(user!=null)
					GetDataFromServers(user.getId());
				//ChallengesArenaActivity.this.user = user;
				updateUI();
			}
		});


		loginButton.setReadPermissions(Arrays.asList("user_friends"));   /*setting permissions*/

		profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);


	}

	@Override
	protected void onResume() {
		super.onResume();
		//uiHelper.onResume();

		// Call the 'activateApp' method to log an app event for use in analytics and advertising reporting.  Do so in
		// the onResume methods of the primary Activities that an app may be launched into.
		//AppEventsLogger.activateApp(this);

		//GetDataFromServers(userId);

		updateUI();

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);

		outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
	}


	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();

		// Call the 'deactivateApp' method to log an app event for use in analytics and advertising
		// reporting.  Do so in the onPause methods of the primary Activities that an app may be launched into.
		//AppEventsLogger.deactivateApp(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
		if (pendingAction != PendingAction.NONE &&
				(exception instanceof FacebookOperationCanceledException ||
						exception instanceof FacebookAuthorizationException)) {
			new AlertDialog.Builder(ChallengesArenaActivity.this)
			.setTitle(R.string.cancelled)
			.setMessage(R.string.permission_not_granted)
			.setPositiveButton(R.string.ok, null)
			.show();
			pendingAction = PendingAction.NONE;
		} 
		updateUI();
	}


	private void GetDataFromServers(String userId)
	{

		GetUserDataFomServer(userId);

	}

	private void updateUI() {


		Session session = Session.getActiveSession();
		boolean enableButtons = (session != null && session.isOpened());

		if (enableButtons && userData != null ) {
			profilePictureView.setProfileId(userData.userData.userId.toString());

			if(ChallengeLevelExists())
			{
				button2.setVisibility(View.VISIBLE);

				radioGroup.setVisibility(View.GONE);
				firendlist.setVisibility(View.GONE);
				challengelist.setVisibility(View.GONE);
			}
			else
			{
				button2.setVisibility(View.GONE);

				radioGroup.setVisibility(View.VISIBLE);

				int radioButtonId = radioGroup.getCheckedRadioButtonId();
				View radioButton = radioGroup.findViewById(radioButtonId);
				int idx = radioGroup.indexOfChild(radioButton);
				if(idx == 0)
				{
					firendlist.setVisibility(View.VISIBLE);
					challengelist.setVisibility(View.GONE);
				}
				else
				{
					firendlist.setVisibility(View.GONE);
					challengelist.setVisibility(View.VISIBLE);
				}

			}

			//GetFriendsListFomFB(session);
			//GetUserDataFomServer();

		} 
		else 
		{
			profilePictureView.setProfileId(null);
			radioGroup.setVisibility(View.GONE);
			button2.setVisibility(View.GONE);
			firendlist.setVisibility(View.GONE);
			challengelist.setVisibility(View.GONE);
		}
	}



	public void GetFriendsListFomFB(Session session) {
		Bundle params = new Bundle();
		params.putString("fields","id, name, picture.width(" + 100 + ").height(" + 100 + ")");

		new Request(
				session,
				"/me/friends",
				params,
				HttpMethod.GET,
				new Request.Callback() {
					public void onCompleted(Response response) {
						ParseGetFriendsListFomFBResponse(response);
					}
				}
				).executeAsync();
	}


	public void ParseGetFriendsListFomFBResponse(Response response) 
	{
		if(friendsList == null)
			friendsList = new FriendsList();
		else
			friendsList.clear();



		GraphObject graphObject = response.getGraphObject();

		if (graphObject != null) {
			JSONObject jsonObject = graphObject.getInnerJSONObject();
			try {
				JSONArray array = jsonObject.getJSONArray("data");

				StringBuilder sb = new StringBuilder();

				for (int i = 0; i < array.length(); i++) {
					JSONObject object = (JSONObject) array.get(i);

					FriendToChallengItem tmpFriend = new FriendToChallengItem();
					String friendId = object.get("id").toString();
					tmpFriend.setId(friendId);
					sb.append(friendId+",");
					tmpFriend.setName(object.get("name").toString());

					try {

						JSONObject pictureObject = (JSONObject) object.get("picture");
						JSONObject dataObject = (JSONObject) pictureObject.get("data");
						tmpFriend.setImagePath(dataObject.get("url").toString());

					} catch (Exception e) {
						// TODO: handle exception
					}

					friendsList.add(tmpFriend);

				}

				GetFriendsDifficultyLevelsFomServer(sb.toString());

				GetChallengesMetaDataFomServer();


				if(FriendsToChallengeAdapter == null)
				{
					FriendsToChallengeAdapter = new FriendsToChallengeAdapter(this,R.layout.friend_to_challenge_item);
				}

				if(!FriendsToChallengeAdapter.isEmpty())
					FriendsToChallengeAdapter.clear();	


				FriendsToChallengeAdapter.setItems(friendsList);

				FriendsToChallengeAdapter.notifyDataSetChanged();

				FriendsToChallengeListView.setAdapter(FriendsToChallengeAdapter);

				Spinner spinner = (Spinner) findViewById(R.id.sort_by1);

				ComparatorAdapter spinnerArrayAdapter = new ComparatorAdapter(this, R.layout.spinner_row, R.id.ComparatorTitle, FriendsToChallengeAdapter.GetComparators());

				spinnerArrayAdapter.setOnOrderChanged(new OnClickListener() {

					@Override
					public void onClick(View v) {
						FriendsToChallengeAdapter.RefreshComperator();

					}


				});
				spinner.setAdapter(spinnerArrayAdapter);

				spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
					@Override
					public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
						FriendsToChallengeAdapter.SetComparator(position);
					}

					@Override
					public void onNothingSelected(AdapterView<?> parentView) {

					}

				});

				FriendsToChallengeListView.setOnItemClickListener(new OnItemClickListener()
				{

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {

						if (userData == null) 
						{
							return;
						}
						final FriendToChallengItem item = FriendsToChallengeAdapter.getItem(position);

						LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						final View stagePickerLayout = inflater.inflate(R.layout.challeng_picker, (ViewGroup) ((Activity)context).findViewById(R.id.mainLL));


						userData.userData.score = Tools.GetUserScore(userData.userData.rank, userData.userData.stage);

						final NumberPicker aNumberPicker = (NumberPicker) stagePickerLayout.findViewById(R.id.stageNumberPicker);

						final TextView currentWinRankTV = (TextView) stagePickerLayout.findViewById(R.id.afterWinRank);
						final TextView afterWinRankTV = (TextView) stagePickerLayout.findViewById(R.id.afterWinRank);
						final TextView afterLoseRankTV = (TextView) stagePickerLayout.findViewById(R.id.afterLoseRank);
						final TextView currentWinScoreTV = (TextView) stagePickerLayout.findViewById(R.id.afterWinScore);
						final TextView afterWinScoreTV = (TextView) stagePickerLayout.findViewById(R.id.afterWinScore);
						final TextView afterLoseScoreTV = (TextView) stagePickerLayout.findViewById(R.id.afterLoseScore);


						int max = Math.min(userData.userData.stage,item.GetDifficultyLevel());
						aNumberPicker.setMaxValue(max);
						aNumberPicker.setMinValue(1);
						aNumberPicker.setValue(max/2);

						int currLevelPicked = aNumberPicker.getValue();

						float afterWinRank = Tools.GetUserRank(userData.userData.winningPoints + currLevelPicked , userData.userData.losingPoints);
						float afterLoseRank = Tools.GetUserRank(userData.userData.winningPoints, userData.userData.losingPoints + currLevelPicked);

						currentWinRankTV.setText(String.format(getString(R.string.stat_rank), userData.userData.rank));
						afterWinRankTV.setText(String.format(getString(R.string.stat_rank), afterWinRank - userData.userData.rank));
						afterLoseRankTV.setText(String.format(getString(R.string.stat_rank), afterLoseRank - userData.userData.rank));

						currentWinScoreTV.setText(String.format(getString(R.string.stat_score), userData.userData.score));
						if(userData.userData.stage == currLevelPicked)
						{
							afterWinScoreTV.setText(String.format(getString(R.string.stat_score), Tools.GetUserScore(afterWinRank, userData.userData.stage+1)));		
						}
						else
						{
							afterWinScoreTV.setText(String.format(getString(R.string.stat_score), Tools.GetUserScore(afterWinRank, userData.userData.stage)));
						}
						afterLoseScoreTV.setText(String.format(getString(R.string.stat_score), Tools.GetUserScore(afterLoseRank, userData.userData.stage)));

						aNumberPicker.setOnValueChangedListener(new OnValueChangeListener() {

							@Override
							public void onValueChange(NumberPicker picker, int oldVal, int newVal) {

								float afterWinRank = Tools.GetUserRank(userData.userData.winningPoints + newVal , userData.userData.losingPoints);
								float afterLoseRank = Tools.GetUserRank(userData.userData.winningPoints, userData.userData.losingPoints + newVal);

								afterWinRankTV.setText(String.format(getString(R.string.stat_rank), afterWinRank - userData.userData.rank));
								afterLoseRankTV.setText(String.format(getString(R.string.stat_rank), afterLoseRank - userData.userData.rank));

								if(userData.userData.stage == newVal)
								{
									afterWinScoreTV.setText(String.format(getString(R.string.stat_score), Tools.GetUserScore(afterWinRank, userData.userData.stage+1)));		
								}
								else
								{
									afterWinScoreTV.setText(String.format(getString(R.string.stat_score), Tools.GetUserScore(afterWinRank, userData.userData.stage)));
								}
								afterLoseScoreTV.setText(String.format(getString(R.string.stat_score), Tools.GetUserScore(afterLoseRank, userData.userData.stage)));

							}
						});

						RelativeLayout.LayoutParams numPicerParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
						numPicerParams.addRule(RelativeLayout.CENTER_HORIZONTAL);

						CustomPopupWindow cpw = new CustomPopupWindow(context);
						cpw.
						setTitle(getString(R.string.select_level_number)).
						AddSpecialView(stagePickerLayout,numPicerParams).
						setPositiveButton(true, getString(R.string.play), 0, new OnClickListener() {
							@Override
							public void onClick(View v) {
								lvl = new ChallengerLevel(userData.userData.userId, item.getId(), aNumberPicker.getValue());


								Intent intent = new Intent(getBaseContext(), ChallengerActivity.class);

								String jsonLevel = StoreChallengeLevel();
								intent.putExtra("PreparedChallengeLevel", jsonLevel);

								Gson gson = new Gson();
								String jsonUserData =  gson.toJson(userData.userData);
								intent.putExtra("PreparedUserData", jsonUserData);

								startActivityForResult(intent, CHALLENGER_REQUEST_CODE);

							}
						}).
						setNegativeButton(true, getString(R.string.cancel),0,  null).
						setCancelable(null).
						Show();

					}
				});


			} catch (JSONException e) {

				e.printStackTrace();
			}
		}

		updateUI();
	}


	public void GetChallengesMetaDataFomServer() {
		new GetDataAsyncTask(new IGetDataResponse() {

			@Override
			public void GetResponse(String res) 
			{
				if(res.startsWith("Error"))
				{
					Toast.makeText(context, res, Toast.LENGTH_LONG).show();
				}
				else
				{

					try {
						ParseGetChallengesMetaDataFomServerResponse(res);
					}

					catch (Exception e) 
					{
						// TODO: handle exception
					}
				}

			}


		}).execute("http://karmeloz.no-ip.org/ctn/rest/challenge/all",userData.userData.userId.toString());
	}

	public void GetUserDataFomServer(String userId) {
		new GetDataAsyncTask(new IGetDataResponse() {

			@Override
			public void GetResponse(String res) 
			{
				if(res.startsWith("Error"))
				{
					Toast.makeText(context, res, Toast.LENGTH_LONG).show();
				}
				else
				{

					try {
						ParseGetUserDataFomServerResponse(res);
					}

					catch (Exception e) 
					{
						// TODO: handle exception
					}
				}

			}

		}).execute("http://karmeloz.no-ip.org/ctn/rest/user",userId);
	}

	public void GetChallengeFomServer(final long Id) {
		new GetDataAsyncTask(new IGetDataResponse() {

			@Override
			public void GetResponse(String res) 
			{
				if(res.startsWith("Error"))
				{
					Toast.makeText(context, res, Toast.LENGTH_LONG).show();
				}
				else
				{

					try {
						ParseGetChallengeFomServerResponse(res, Id);
					}

					catch (Exception e) 
					{
						// TODO: handle exception
					}
				}

			}


		}).execute("http://karmeloz.no-ip.org/ctn/rest/challenge?challengeId="+Id,userData.userData.userId.toString());
	}

	public void GetFriendsDifficultyLevelsFomServer(String postFriendsDifficultyLevelsRequest) {
		new GetDataAsyncTask(new IGetDataResponse() {

			@Override
			public void GetResponse(String res) {
				if(res.startsWith("Error"))
				{
					Toast.makeText(context, res, Toast.LENGTH_LONG).show();
				}
				else
				{

					ParseFriendsDifficultyLevelsResponse(res);
				}
			}

		}).execute("http://karmeloz.no-ip.org/ctn/rest/friend/all",String.valueOf(userData.userData.userId),postFriendsDifficultyLevelsRequest);
	}

	public void ParseFriendsDifficultyLevelsResponse(String res) {
		final Gson gson = new Gson();
		try {
			Get_FriendsDifficultyLevels gettFriendsDifficultyLevelResponse = gson.fromJson(res, Get_FriendsDifficultyLevels.class);

			for (FriendDifficultyLevel FriendDifficultyLevel : gettFriendsDifficultyLevelResponse.friendsDifficultyLevels)
			{
				friendsList.setStage(FriendDifficultyLevel.userId, FriendDifficultyLevel.stage);
			}

			FriendsToChallengeAdapter.notifyDataSetChanged();
		} catch (Exception e) {
			// TODO: handle exception
		}

		updateUI();


	}

	public void PostChallengeToServer(GetPost_Challenge challenge) {
		Gson gson = new Gson();
		String json = gson.toJson(challenge);
		new PostDataAsyncTask(new IPostDataResponse() {

			@Override
			public void PostResponse(String res) {
				if(res.startsWith("Error"))
				{
					Toast.makeText(context, res, Toast.LENGTH_LONG).show();
				}
				else
				{
					DeleteChallengeLevel();
					lvl = null;
					//updateUI();
				}


			}
		}).execute("http://karmeloz.no-ip.org/ctn/rest/challenge",String.valueOf(challenge.challenge.senderUserId),json);
	}


	public void ParseGetChallengesMetaDataFomServerResponse(
			String res) throws JSONException {

		if(ChallengesMetaDataList == null)
			ChallengesMetaDataList = new ArrayList<ChallengeMetaDataItem>();
		else
			ChallengesMetaDataList.clear();

		Gson gson = new Gson();
		Get_ChallengesMetaDatas gettChallengesMetaDatasResponse = gson.fromJson(res, Get_ChallengesMetaDatas.class);

		for (int i = 0; i < gettChallengesMetaDatasResponse.challengesMetaDatas.size(); i++) 
		{
			ChallengeMetaData item = gettChallengesMetaDatasResponse.challengesMetaDatas.get(i);
			ChallengeMetaDataItem tmpChallengeMetaData = new ChallengeMetaDataItem();

			tmpChallengeMetaData.setId(item.challengeId);
			tmpChallengeMetaData.setChallengerId(item.senderUserId);
			tmpChallengeMetaData.setDifficultyLevel(item.difficultyLevel);
			try {
				tmpChallengeMetaData.setName(friendsList.GetFriendName(item.senderUserId));
				tmpChallengeMetaData.setBitmap(friendsList.GetFriendBitmap(item.senderUserId));
				tmpChallengeMetaData.setImagePath(friendsList.GetFriendImagePath(item.senderUserId));

			} catch (Exception e) {
				// TODO: handle exception
			}


			ChallengesMetaDataList.add(tmpChallengeMetaData);

		}


		ChallengesMetaDataListView = (ListView) findViewById(R.id.listView_ChallengesMetaData);
		if(ChallengesMetaDataAdapter == null)
		{
			ChallengesMetaDataAdapter = new ChallengeMetaDataAdapter(context,R.layout.challenge_metadata_item);
		}

		if(!ChallengesMetaDataAdapter.isEmpty())
			ChallengesMetaDataAdapter.clear();	

		ChallengesMetaDataListView.setAdapter(ChallengesMetaDataAdapter);



		ChallengesMetaDataAdapter.setItems(ChallengesMetaDataList);

		ChallengesMetaDataAdapter.notifyDataSetChanged();

		ChallengesMetaDataListView.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				final ChallengeMetaDataItem item = ChallengesMetaDataAdapter.getItem(position);
				GetChallengeFomServer(item.getId());
			}
		});





		Spinner spinner = (Spinner) findViewById(R.id.sort_by2);

		ComparatorAdapter spinnerArrayAdapter = new ComparatorAdapter(this, R.layout.spinner_row, R.id.ComparatorTitle, ChallengesMetaDataAdapter.GetComparators());

		spinnerArrayAdapter.setOnOrderChanged(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ChallengesMetaDataAdapter.RefreshComperator();

			}


		});
		spinner.setAdapter(spinnerArrayAdapter);

		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
				ChallengesMetaDataAdapter.SetComparator(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parentView) {

			}

		});

		updateUI();

	}




	public void ParseGetUserDataFomServerResponse(String res) throws JSONException
	{
		Gson gson = new Gson();
		userData = gson.fromJson(res, Get_UserData.class);

		userData.userData.rank = Tools.GetUserRank(userData.userData.winningPoints, userData.userData.losingPoints);

		userData.userData.score = Tools.GetUserScore(userData.userData.rank, userData.userData.stage);

		Session session = Session.getActiveSession();
		if(session != null && session.isOpened())
		{
			GetFriendsListFomFB(session);
		}

		updateUI();
	}

	public void ParseGetChallengeFomServerResponse(	String res, long Id) throws JSONException {


		GetPost_Challenge objres= new GetPost_Challenge();


		Gson gson = new Gson();
		objres = gson.fromJson(res, GetPost_Challenge.class);

		objres.challenge.challengeId = Id;
		lvl = new ChallengeeLevel(objres.challenge);


		Intent intent = new Intent(getBaseContext(), ChallengeeActivity.class);

		String jsonLevel = StoreChallengeLevel();
		intent.putExtra("PreparedChallengeLevel", jsonLevel);

		String jsonUserData =  gson.toJson(userData.userData);
		intent.putExtra("PreparedUserData", jsonUserData);

		startActivityForResult(intent, CHALLENGEE_REQUEST_CODE);


	}


	public String StoreChallengeLevel()
	{
		return lvl.StoreLevel(context, "ChallengeInfo");
	}


	private void SendResultToServer(ChallengerLevel tempcompleteLevel) {

		GetPost_Challenge challenge = new GetPost_Challenge();
		if(tempcompleteLevel instanceof ChallengeeLevel)
		{
			challenge.challenge.challengeId = ((ChallengeeLevel)tempcompleteLevel).getChallengeId();
		}
		challenge.challenge.difficultyLevel = tempcompleteLevel.getStage();
		challenge.challenge.numbers = tempcompleteLevel.getListOfNumbers();
		challenge.challenge.goal = tempcompleteLevel.getGoal();
		challenge.challenge.timeInSeconds = tempcompleteLevel.getTimeinSec();
		challenge.challenge.senderUserId = tempcompleteLevel.getChallengerId();
		challenge.challenge.receiverUserId = tempcompleteLevel.getChallengeeId();
		challenge.challenge.solution = tempcompleteLevel.getSolution();
		challenge.challenge.diff = 0;//TODO

		PostChallengeToServer(challenge);
	}


	@Override 
	public void onActivityResult(int requestCode, int resultCode, Intent data) {     
		super.onActivityResult(requestCode, resultCode, data); 
		uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
		switch(requestCode) { 
		case (CHALLENGER_REQUEST_CODE) :
		case (CHALLENGEE_REQUEST_CODE) :
		{ 
			if (resultCode == Activity.RESULT_OK) { 
				Bundle extras = data.getExtras();
				if(extras != null)
				{				

					String completeLevelImage = "";
					if(extras.containsKey("completeLevelImage"))
						completeLevelImage = extras.getString("completeLevelImage");

					ChallengerLevel tempcompleteLevel = null;
					if(requestCode == CHALLENGER_REQUEST_CODE)
						tempcompleteLevel = (ChallengerLevel) Level.fromJson(completeLevelImage, ChallengerLevel.class);
					else
						tempcompleteLevel = (ChallengeeLevel) Level.fromJson(completeLevelImage, ChallengeeLevel.class);

					if(tempcompleteLevel != null)
					{

						tempcompleteLevel.StoreLevel(context, "ChallengeInfo");
						lvl = tempcompleteLevel;

						SendResultToServer(tempcompleteLevel);

					}



					updateUI();
				}
			} 
			break; 
		} 

		} 

	}
}


